package com.changgou.file.controller;

import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.file.pojo.FastDFSClient;
import com.changgou.file.pojo.FastDFSFile;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/file")
public class FileController {
    @PostMapping("/upload")
    public Result upload(MultipartFile file) {
        try {
            //判断文件是否存在
            if (file == null) {
                return new Result(false, StatusCode.ERROR, "文件上传失败");
            }
            //获取文件全名
            String originalFilename = file.getOriginalFilename();
            if (StringUtils.isEmpty(originalFilename)) {
                return new Result(false, StatusCode.ERROR, "文件上传失败");
            }
            //获取文件扩展名
            String ExName = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
            //获取文件内容
            byte[] fileBytes = file.getBytes();
            //封装实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, fileBytes, ExName);
            //利用工具类上传文件，接收结果
            //接收2个结果，一个是存入的组名，一个是文件的路径
            String[] upload = FastDFSClient.upload(fastDFSFile);
            String url = FastDFSClient.getTrackerUrl() + upload[0] + "/" + upload[1];
            return new Result(true, StatusCode.OK, "文件上传成功",url);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, StatusCode.ERROR, "上传失败");
        }

    }
}
